package com.siwei.mes.common.exception.handler;

import java.util.function.Supplier;

/**
 * @author chenmaolin
 * @create 2021-12-08 9:22
 */
public class Singleton<R> implements Supplier {
    private boolean initialized = false;
    private volatile Supplier<R> instanceSupplier;

    public Singleton(Supplier<R> original) {
        this.instanceSupplier = () -> {
            synchronized (original) {
                if (!this.initialized) {
                    R singletonInstance = original.get();
                    this.instanceSupplier = () -> {
                        return singletonInstance;
                    };
                    this.initialized = true;
                }

                return this.instanceSupplier.get();
            }
        };
    }

    @Override
    public R get() {
        return this.instanceSupplier.get();
    }
}
